package com.vietnam.power.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import com.vietnam.power.dao.UserDao;
import com.vietnam.power.persistence.UserInfo;

@Component(value = "authenticationProvider")
public class CustomAuthenticationProvider extends DaoAuthenticationProvider {

	@Autowired
	private UserDao userDao;

	@Autowired
	@Override
	@Qualifier(value = "loginService")
	public void setUserDetailsService(UserDetailsService userDetailsService) {
		super.setUserDetailsService(userDetailsService);
	}

	@Override
	@Qualifier(value = "encoder")
	@Autowired
	public void setPasswordEncoder(Object passwordEncoder) {
		super.setPasswordEncoder(passwordEncoder);
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		try {
			Authentication auth = super.authenticate(authentication);
			// reset login count when authenticate successfully.
			//UserInfo userInfo = userDao.getUserByUserName(authentication.getName());
			//userInfo.setLoginAttempts((short) 0);
			//userInfo.setUpdatedDate(DateTimeUtil.getCurrentDateByTimezone(userInfo.getTimezone()));
			//userDao.updateUserInfo(userInfo);

			return auth;
		} catch (BadCredentialsException e) {
			// invalid login, update to user_attempts
			UserInfo userInfo = userDao.getUserByUserName(authentication.getName());
			// get login attempts
			//short logginAttempts = (short) (userInfo.getLoginAttempts() + (short) 1);
			// if try more than max, set account to lock.
			//if (logginAttempts > AppConfigurationConstant.USER_INFO.MAX_OF_LOGGING_ATTEMPT) {
				//userInfo.setAccountNonLocked(false);
			//}

			//userInfo.setLoginAttempts(logginAttempts);
			//userInfo.setUpdatedDate(DateTimeUtil.getCurrentDateByTimezone(userInfo.getTimezone()));
			// update account
			//userDao.updateUserInfo(userInfo);

			throw e;
		} catch (LockedException e) {
			throw e;
		} catch (AccountExpiredException e) {
			throw e;
		} catch (CredentialsExpiredException e) {
			throw e;
		}
	}
}
